package com.zjdiepu.www.biz.dh;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.BaseException;
import com.zjdiepu.www.base.core.BaseService;
import com.zjdiepu.www.base.enums.type.ModeIDType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.dao.base.SysUserMapper;
import com.zjdiepu.www.dao.dh.FkInsureListMapper;
import com.zjdiepu.www.dao.other.OtherTaskAllocationMapper;
import com.zjdiepu.www.ibiz.dh.IFkInsureListService;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.base.ext.SysUserExt;
import com.zjdiepu.www.model.dh.dto.FkInsureList;
import com.zjdiepu.www.model.dh.ext.FkInsureListExt;
import com.zjdiepu.www.model.other.dto.OtherTaskAllocation;

/**
 * 待投保列表Service层操作实现<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年05月17日 14时25分<br/>
 * @since 1.0<br/>
 */
@Service
public class FkInsureListServiceImpl extends BaseService implements IFkInsureListService {
	public static final Logger logger = LoggerFactory.getLogger(FkInsureListServiceImpl.class);

	@Autowired
	private FkInsureListMapper fkInsureListMapper;
	@Autowired
	private SysUserMapper sysUserMapper;
	@Autowired
	private OtherTaskAllocationMapper otherTaskAllocationMapper;
	@Override
	public ApiResponse saveAllocation(String id, String operatorId,
			String operatorName, AbstractSysUser currentUser) {
		FkInsureList fkInsureList = new FkInsureList();
		String userId = currentUser.getId();
		String userName=  currentUser.getName();
    	fkInsureList.initUpdateData(userId, userName);
    	fkInsureList.setOperatorId(operatorId);
    	fkInsureList.setOperatorName(operatorName);
    	fkInsureList.setAcceptDate(new Date());
    	List<String> ids = Arrays.asList(id.split(","));
    	fkInsureListMapper.updateCommonBatch(fkInsureList, ids);
    	List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
    	for(String id_ : ids) {
    		OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
    		otherTaskAllocation.initInsertData(userId, userName);
    		otherTaskAllocation.setModeId(ModeIDType.TOUBAO.getCode());
    		otherTaskAllocation.setDataid(id_.trim());
    		otherTaskAllocation.setAlloterId(currentUser.getId());
    		otherTaskAllocation.setAlloterName(currentUser.getName());
    		otherTaskAllocation.setReceiverId(operatorId);
    		otherTaskAllocation.setReceiverName(operatorName);
    		otherTaskAllocations.add(otherTaskAllocation);
    	}
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
    	return ApiResponse.success(true);
	}
	@Override
	public void updateForApplyAllocation(int allocationNum, SysUser sysUser) {
    	FkInsureListExt fkInsureListExt = new FkInsureListExt();
		fkInsureListExt.withOutPage();
        fkInsureListExt.setBaseWhere();
        fkInsureListExt.notAllocation();
        List<FkInsureList> fkInsureLists = fkInsureListMapper.selectByExt(fkInsureListExt);
        
        Random random = new Random();
        int fkInsureListCounts = fkInsureLists.size();
        List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
		for(int i = 0; i < allocationNum && fkInsureListCounts > 0; i++) {
        	int nextBusinessInt = random.nextInt(fkInsureListCounts);
        	FkInsureList randomFkInsureList = fkInsureLists.get(nextBusinessInt);
        	randomFkInsureList.initUpdateData(sysUser.getId(), sysUser.getName());
        	randomFkInsureList.setOperatorId(sysUser.getId());
        	randomFkInsureList.setOperatorName(sysUser.getUname());
        	randomFkInsureList.setAcceptDate(new Date());
        	
        	fkInsureLists.remove(randomFkInsureList);
        	fkInsureListCounts--;
        	
        	OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
    		otherTaskAllocation.initInsertData(sysUser.getId(), sysUser.getName());
    		otherTaskAllocation.setModeId(ModeIDType.TOUBAO.getCode());
    		otherTaskAllocation.setDataid(randomFkInsureList.getId());
    		otherTaskAllocation.setAlloterId(sysUser.getId());
    		otherTaskAllocation.setAlloterName(sysUser.getName());
    		otherTaskAllocation.setReceiverId(sysUser.getId());
    		otherTaskAllocation.setReceiverName(sysUser.getUname());
    		otherTaskAllocations.add(otherTaskAllocation);
        	
        	fkInsureListMapper.updateByPrimaryKeySelective(randomFkInsureList);
		}
		
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
		
	}
	@Override
	public void updateForRandomAllocation(int allocationNum, SysUser sysUser) {
		String orgId = sysUser.getOrgId();
    	SysUserExt sysUserExt = new SysUserExt();
    	sysUserExt.setBaseWhere();
    	sysUserExt.withOutPage();
    	sysUserExt.setOrgId(orgId);
    	List<SysUser> sysUsers = sysUserMapper.selectByExt(sysUserExt);
    	int userCounts = sysUsers.size();
    	
    	Random random = new Random();
    	FkInsureListExt fkInsureListExt = new FkInsureListExt();
    	fkInsureListExt.withOutPage();
        fkInsureListExt.setBaseWhere();
        fkInsureListExt.notAllocation();
        List<FkInsureList> fkInsureLists = fkInsureListMapper.selectByExt(fkInsureListExt);
        int fkInsureListCounts = fkInsureLists.size();
        List<OtherTaskAllocation> otherTaskAllocations = new ArrayList<OtherTaskAllocation>();
    	if(userCounts > 0) {
    		for(int i = 0; i < allocationNum && fkInsureListCounts > 0; i++) {
	    		int nextUserIndex = random.nextInt(userCounts);
	    		SysUser randomUser = sysUsers.get(nextUserIndex);
	        	int nextBusinessInt = random.nextInt(fkInsureListCounts);
	        	FkInsureList randomFkInsureList = fkInsureLists.get(nextBusinessInt);
	        	randomFkInsureList.initUpdateData(sysUser.getId(), sysUser.getName());
	        	randomFkInsureList.setOperatorId(randomUser.getId());
	        	randomFkInsureList.setOperatorName(randomUser.getUname());
	        	randomFkInsureList.setAcceptDate(new Date());
	        	
	        	fkInsureLists.remove(randomFkInsureList);
	        	fkInsureListCounts--;
	        	
	        	OtherTaskAllocation otherTaskAllocation = new OtherTaskAllocation();
	    		otherTaskAllocation.initInsertData(sysUser.getId(), sysUser.getName());
	    		otherTaskAllocation.setModeId(ModeIDType.TOUBAO.getCode());
	    		otherTaskAllocation.setDataid(randomFkInsureList.getId());
	    		otherTaskAllocation.setAlloterId(sysUser.getId());
	    		otherTaskAllocation.setAlloterName(sysUser.getName());
	    		otherTaskAllocation.setReceiverId(randomUser.getId());
	    		otherTaskAllocation.setReceiverName(randomUser.getUname());
	    		otherTaskAllocations.add(otherTaskAllocation);
	        	
	        	fkInsureListMapper.updateByPrimaryKeySelective(randomFkInsureList);
    		}
    	}
    	
    	if(CollectionUtils.isNotEmpty(otherTaskAllocations)){
    		otherTaskAllocationMapper.insertBatch(otherTaskAllocations);
    	}
		
	}
	
	@Override
	public void saveUpdateAndDelete(FkInsureList fkInsureList, OperateType operType) {
		switch (operType) {
		case add:
			fkInsureList.initInsertData(fkInsureList.getModifier(), fkInsureList.getModifierName());
			fkInsureListMapper.insert(fkInsureList);
			break;
		case edit:
			fkInsureList.initUpdateData(fkInsureList.getModifier(), fkInsureList.getModifierName());
			// 影响的记录数
			int updateCount = fkInsureListMapper.updateByPrimaryKeySelective(fkInsureList);
			if(updateCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(updateCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		case delete:
			fkInsureList.initDeleteData(fkInsureList.getModifier(), fkInsureList.getModifierName());
			// 影响的记录数
			int deleteCount = fkInsureListMapper.updateByPrimaryKeySelective(fkInsureList);
			if(deleteCount == 0){
				throw new BaseException(ResultFlagType.MISSING.getCode().toString(),ResultFlagType.MISSING.getValue());
			} else if(deleteCount > 1){
				throw new BaseException(ResultFlagType.MULTI_DATA.getCode().toString(),ResultFlagType.MULTI_DATA.getValue());
			}
			break;
		default:
			break;
		}
	}
	
	@Override
	public List<FkInsureList> selectByExt(FkInsureListExt fkInsureListExt) {
		return fkInsureListMapper.selectByExt(fkInsureListExt);
	}
	
	@Override
	public int countByExt(FkInsureListExt fkInsureListExt){
		return fkInsureListMapper.countByExt(fkInsureListExt);
	}
	
	@Override
	public FkInsureList selectById(String id) {
		return fkInsureListMapper.selectByPrimaryKey(id);
	}
	
	@Override
	public void clearEmpty(Set<String> fieldNames, String id) {
		if(CollectionUtils.isNotEmpty(fieldNames)){
			fkInsureListMapper.clearEmpty(fieldNames, id);
		}
	}
	
	@Override
	public int countRefined(FkInsureList fkInsureList) {
		return fkInsureListMapper.countRefined(fkInsureList);
	}

	@Override
	public FkInsureList selectRefined(FkInsureList fkInsureList) {
		return fkInsureListMapper.selectRefined(fkInsureList);
	}
	
	@Override
	public int deletedRefined(FkInsureList fkInsureList) {
		return fkInsureListMapper.deletedRefined(fkInsureList);
	}

	@Override
	public boolean repeat(FkInsureList fkInsureList) {
		int count = countRefined(fkInsureList);
		if(count > 1) {
			return true;
		}
		if(count == 0) {
			return false;
		}
		
		if(StringUtils.isBlank(fkInsureList.getId())) {
			return true;
		}
		FkInsureList dbItem = selectRefined(fkInsureList);
		if(null == dbItem) {
			return false;
		}
		return !fkInsureList.getId().equals(dbItem.getId());
	}
	
	@Override
	public int updateBatch(String modifier, String modifierName, Integer dpStatus, List<String> ids) {
		Integer current = (int)(System.currentTimeMillis() / 1000);
		return fkInsureListMapper.updateBatch(modifier, modifierName, current, dpStatus, ids);
	}
	
	@Override
	public int insertBatch(List<FkInsureList> fkInsureLists) {
		return fkInsureListMapper.insertBatch(fkInsureLists);
	}
}
